package com.lvmama.controller.rhino.system;

import com.lvmama.client.rhino.MenuClient;
import com.lvmama.client.rhino.RoleClient;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.JSONConversionUtil;
import com.lvmama.pojo.base.Page;
import com.lvmama.pojo.dto.rhino.system.MenuTreeVO;
import com.lvmama.pojo.dto.rhino.system.RoleDTO;
import com.lvmama.pojo.dto.rhino.system.RoleQueryDTO;
import com.lvmama.pojo.entity.rhino.system.Menu;
import com.lvmama.pojo.entity.rhino.system.Role;
import com.lvmama.pojo.entity.rhino.system.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName : RoleController
 * @Description : 角色管理
 * @Author :Administrator
 * @Date : 2018/8/23 17:17
 * @Version V1.0
 **/
@Slf4j
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleClient roleClient;
    @Autowired
    private MenuClient menuClient;

    /**
     * 查询角色列表
     * @param model
     * @param queryDTO
     * @return 角色列表页面
     */
    @RequestMapping(value = "/roleList",method = RequestMethod.GET)
    public String roleList(Model model,RoleQueryDTO queryDTO){
        queryDTO.setPage(true);
        queryDTO.setLimit(queryDTO.getLimit());
        Result<Page<Role>> page = roleClient.getRolePage(queryDTO);
        model.addAttribute("page",page.getData());
        return "/system/roleList";
    }

    /**
     * 新增角色页
     * @param request
     * @param model
     * @return 新增角色页面
     */
    @RequestMapping(value = "/newRole",method = RequestMethod.GET)
    public String  newRole(HttpServletRequest request, Model model ){
        log.info("RoleController newRole start");
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        List<Menu> menusList = menuClient.getAllMenuListByUser(currentUser).getData();
        if(menusList!=null&&menusList.size()>0){
            List<MenuTreeVO> menuTree = menusList.stream().map(MenuTreeVO::new).collect(Collectors.toList());
            String menus = JSONConversionUtil.objToString(menuTree);
            model.addAttribute("menus",menus);
        }
        model.addAttribute("role",new Role());
        log.info("RoleController newRole end");
        return "system/roleForm";
    }

    /**
     * 保存角色
     * @param roleDTO
     * @return
     */
    @RequestMapping(value = "/saveRole",method = RequestMethod.POST)
    @ResponseBody
    public Result saveRole(RoleDTO roleDTO){
        log.info("RoleController saveRole start");
        RoleQueryDTO query = new RoleQueryDTO();
        query.setName(roleDTO.getName());
        List<Role> result = roleClient.getRoleInfo(query).getData();
        if (result!=null &&result.size()>0 && roleDTO.getId() == null) {
            return Result.error(CodeMessage.ROLE_EXIST);
        }
        if(roleDTO.getId()==null){
            //保存新角色
            roleDTO.setUseable("1");
            roleClient.saveRoleByRoleDTO(roleDTO);
        }else {
            //保存角色编辑
            roleClient.updateRoleByRoleDTO(roleDTO);
        }
        log.info("RoleController saveRole end");
        return Result.success(true);
    }

    /**
     * 编辑角色
     * @param model
     * @param roleId
     * @param request
     * @return
     */
    @RequestMapping(value = "editRole",method = RequestMethod.GET)
    public String editRole(Model model,String roleId,HttpServletRequest request){
        log.info("RolecController editRole start into editPage");
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        List<Menu> menusList = menuClient.getAllMenuListByUser(currentUser).getData();
        //查询该角色下所有菜单
        Role role =  roleClient.getRoleMenusByRoleId(roleId).getData();
        if(role!=null && role.getMenuList()!=null){
            model.addAttribute("role", role);
            List<Menu> roleMenus = role.getMenuList();
            List<MenuTreeVO> menuTrees = menusList.stream().map(menu -> {
                MenuTreeVO treeVO = new MenuTreeVO();
                treeVO.setId(menu.getId());
                treeVO.setName(menu.getName());
                treeVO.setpId(menu.getParentId());
                treeVO.setOpen(true);
                treeVO.setChecked(roleMenus.contains(menu));
                return treeVO;
            }).collect(Collectors.toList());
            //把menuTrees转成json字符串
            String menus = JSONConversionUtil.objToString(menuTrees);
            model.addAttribute("menus", menus);
        }else{
            role = roleClient.getRoleById(roleId).getData();
            model.addAttribute("role",role);
            if(menusList!=null&&menusList.size()>0){
                List<MenuTreeVO> menuTree = menusList.stream().map(MenuTreeVO::new).collect(Collectors.toList());
                String menus = JSONConversionUtil.objToString(menuTree);
                model.addAttribute("menus",menus);
            }
        }
        log.info("RolecController editRole end into editPage");
        return "system/roleForm";
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteRole",method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> deleteRole(String id){
        log.info("roleController deleteRole start");
        try {
            roleClient.deleteRoleById(id);
        }catch (Exception e){
            log.error("RoleController deleteRole error:{}",e.getMessage());
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("roleController deleteRole end");
        return Result.success(true);
    }

}